package cn.qiyu5522.tk_ems.utils;

import cn.qiyu5522.tk_ems.exception.BusinessException;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * EasyExcel工具类
 */
public class EasyExcelUtils {

    /**
     * 通过路径，读取excel所有数据
     * @param fileName excel文件路径
     * @param aClass 映射对象class
     * @return 与excel对应的list集合
     */
    public static<T> List<T> getListByPathName(String fileName,Class<?> aClass){

        if (fileName.isEmpty()) {
            return null;
        }
        List<T> list = new ArrayList<>();

        AnalysisEventListener<T> analysisEventListener =  new AnalysisEventListener<T>(){
            @Override
            public void invoke(T obj, AnalysisContext analysisContext) {
                list.add(obj);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {

            }
        };

        EasyExcel.read(fileName,aClass,analysisEventListener).sheet().doRead();
        return list;
    }

    /**
     * 通过流，读取excel所有数据,返回对应的对象list集合
     * @param file excel文件流
     * @param aClass 映射对象class
     * @return 与excel对应的list集合
     */
    public static<T> List<T> getListByFile(MultipartFile file, Class<?> aClass) {

        List<T> list = new ArrayList<>();

        AnalysisEventListener<T> analysisEventListener =  new AnalysisEventListener<T>(){
            @Override
            public void invoke(T obj, AnalysisContext analysisContext) {
                list.add(obj);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {

            }
        };
        try {
            EasyExcel.read(file.getInputStream(),aClass,analysisEventListener).sheet().doRead();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 通过对象list集合得到outPutStream
     * @param List 对象集合
     * @return excel文件流
     */
    public static <T> boolean  setByListToPathName(String pathName, List<T> List) {

        if (pathName.isEmpty() || List.isEmpty()) {
            return false;
        }
        EasyExcel.write(pathName,List.get(0).getClass()).sheet().doWrite(List);
        return true;

    }


    /**
     * 通过对象list写入outputStream
     * @param List 对象集合
     * @return excel文件流
     */
    public static <T> boolean  setByListToOutputStream(OutputStream outputStream, List<T> List) {

        if (List.isEmpty()) {
            return false;
        }
        EasyExcel.write(outputStream,List.get(0).getClass())
                // Java Long 类型转换为 Excel 字符串
                .registerConverter(new LongStringConverter())
                // 注入策略
                .sheet().doWrite(List);
        return true;

    }

    /**
     * 通过EasyExcel的list对象，对response的OutputStream进行填充返回给浏览器
     * @param response HttpServletResponse对象
     * @param fileName 文件名
     * @param easyExcelList EasyExcel的list对象
     * @param <T> 泛型
     * @throws IOException
     */
    public static <T> void resposeEasyExcel(HttpServletResponse response,String fileName,List<T> easyExcelList) throws IOException{

        if (fileName.isEmpty()) {
            throw new BusinessException(400,"文件名不能为空");
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String newfileName = null;
        newfileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + newfileName + ".xlsx");

        setByListToOutputStream(response.getOutputStream(),easyExcelList);

    }

}